package Utils;


import com.my.MyWriter;
import com.my.UserWriter;
import com.my.service.AService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

import java.io.IOException;
import java.io.InputStream;


@ComponentScan("com.my")
@Import(MyImportBeanDefinitionRegistrar.class)
//如何手动添加一个不带注解或者配置文件中没有的类
public class MyApplication {

    //    如果需要使用MyBatis需要配置SqlSessionFactory的bean对象
    @Bean
    public SqlSessionFactory getSqlSessionFactoryBean() {
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            return new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {


//        获取ApplicationContext
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //        创建一个BeanDefinition
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//        将类添加到BeanDefinition中
        beanDefinition.setBeanClass(UserWriter.class);
//        注册BeanDefinition
        context.registerBeanDefinition("user", beanDefinition);

        context.register(MyApplication.class);


        context.refresh();

        UserWriter userWriter = (UserWriter) context.getBean("user");
        MyWriter myWriter = (MyWriter) context.getBean("myWriter");
        System.out.println(userWriter);
        myWriter.test();

//      下面模拟Spring 的依赖注入问题
        AService aService = (AService) context.getBean("aService");
        aService.test();

    }
}
